package com.daxia.bumall.web.controller.admin;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.daxia.bumall.common.AuditStatus;
import com.daxia.bumall.common.UserType;
import com.daxia.bumall.dto.CompanyDTO;
import com.daxia.bumall.dto.DesignerDTO;
import com.daxia.bumall.dto.JsonResultDTO;
import com.daxia.bumall.dto.UserDTO;
import com.daxia.bumall.model.User;
import com.daxia.bumall.service.CompanyService;
import com.daxia.bumall.service.DesignerService;
import com.daxia.bumall.service.UserService;
import com.daxia.bumall.support.Page;
import com.daxia.bumall.util.SpringSecurityUtils;
import com.daxia.bumall.web.controller.BaseController;

@Controller
@RequestMapping(value = "/admin/company", produces="text/html;charset=UTF-8")
public class AdminCompanyController extends BaseController {

	@Autowired
	private CompanyService companyService;
	@Autowired
	private DesignerService designerService;
	@Autowired
	private UserService userService;

	@RequestMapping(value = "/detail")
	public String detail(Map<String, Object> map, Long id) {
		if (id != null) {
			CompanyDTO dto = companyService.load(id);
			map.put("n", dto);
		}
		return "admin/company/company_detail";
	}
	
	@ResponseBody
	@RequestMapping(value = "/save")
	
	public String save(CompanyDTO dto, JsonResultDTO resultDTO) throws Exception {
		if (dto.getId() == null) {
			companyService.create(dto);
		} else {
			dto.setAuditTime(new Date());
			User user = (User) SpringSecurityUtils.getCurrentUser();
			dto.setAuditUser(user);
			companyService.updateForAudit(dto);
		}
		return okAndClose(resultDTO);
	}

    
	@ResponseBody
	@RequestMapping(value = "/delete") 
	public String delete(Long[] ids, JsonResultDTO resultDTO) throws IOException {
		companyService.deleteByIds(ids);
		return okAndRefresh(resultDTO);
	}
	
	@RequestMapping(value = "/list")
	public String list(CompanyDTO dto, Map<String, Object> map, Page page) {
		List<CompanyDTO> dtos = companyService.find(dto, page);
		map.put("list", dtos);
		map.put("query", dto);
		return "admin/company/company_list";
	}
	
	@ResponseBody
	@RequestMapping(value = "/datagrid")
    
    public String datagrid(CompanyDTO dto, Map<String, Object> map, Page page) throws Exception {
        List<CompanyDTO> dtos = companyService.find(dto, page);
        JSONArray jsonArray = new JSONArray();
        for (CompanyDTO company : dtos) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", company.getId());
            jsonObject.put("name", company.getName());
            jsonArray.add(jsonObject);
        }
        JSONObject json = new JSONObject();
        json.put("total", page.getTotalRecords());
        json.put("rows", jsonArray);
        return json.toJSONString();
    }
	
	@RequestMapping(value = "/audit")
	public String audit(CompanyDTO dto, Long designerId, Map<String, Object> map, Page page) {
		DesignerDTO dDto = null;
		if (designerId != null) {
			dDto = designerService.load(designerId);
		}
		User user = (User) SpringSecurityUtils.getCurrentUser();
		if (user.getType() == UserType.City.getValue()) {
			User newUser = new User();
			newUser.setCity(user.getCity());
			dto.setUser(newUser);
		} else {
			dto.setAdmin(true);
			UserDTO query = new UserDTO();
			query.setType(UserType.City.getValue());
			List<UserDTO> list = userService.find(query, null);
			String cityIdArr = "(";
			for (int i = 0; i < list.size() - 1; i++) {
				cityIdArr += list.get(i).getCity().getId();
				if (i != list.size()-2) {
					cityIdArr += ",";
				} else {
					cityIdArr += ") ";
				}
			}
			dto.setCityIdArr(cityIdArr);
		}
		List<CompanyDTO> dtos = companyService.findCompanyHavingPay(dto, page);
		if (null != dDto) {
			for (CompanyDTO m : dtos) {
				if (m.getId() == dDto.getCompanyUser().getId()) {
					m.setChecked(true);
				}
			}
		}
		map.put("list", dtos);
		map.put("query", dto);
		return "admin/company/company_audit";
	}
	
	@RequestMapping(value = "/auditDetail")
	public String auditDetail(Map<String, Object> map, Long id) {
		if (id != null) {
			CompanyDTO dto = companyService.load(id);
			map.put("n", dto);
		}
		map.put("provinces", provinceService.findAll());
		return "admin/company/company_audit_detail";
	}
	
	@Transactional
	@ResponseBody
	@RequestMapping(value = "/saveAudit")
	public String saveAudit(CompanyDTO dto, JsonResultDTO resultDTO) {
		UserDTO userDTO = getCurrentUserDTO();
		if (userDTO.getType() != UserType.Manager.getValue()) {
			throw new RuntimeException("没有权限");
		}

		CompanyDTO old = companyService.load(dto.getId());
		User user = (User) SpringSecurityUtils.getCurrentUser();
		old.setAuditUser(user);
		old.setAuditTime(new Date());
		if (old.getAuditStatus() != AuditStatus.Success.getValue() && dto.getAuditStatus() == AuditStatus.Success.getValue()) {
			// 审核通过
			dispatcherService.onCompanyActivated(old.getUser().getId());
		}
		old.setAuditStatus(dto.getAuditStatus());
		old.setAuditRemark(dto.getAuditRemark());
		
		companyService.updateForAudit(old);
		return okAndClose(resultDTO);
	}
	
	@RequestMapping(value = "/sel")
	public String sel(CompanyDTO dto, Long designerId, Map<String, Object> map, Page page) {
		DesignerDTO dDto = null;
		if (designerId != null) {
			dDto = designerService.load(designerId);
		}
		User user = (User) SpringSecurityUtils.getCurrentUser();
		User newUser = new User();
		newUser.setCity(user.getCity());
		dto.setUser(newUser);
		List<CompanyDTO> dtos = companyService.findCompanyHavingPay(dto, page);
		if (null != dDto && dDto.getCompanyUser() != null) {
			for (CompanyDTO m : dtos) {
				if (m.getId() == dDto.getCompanyUser().getId()) {
					m.setChecked(true);
				}
			}
		}
		map.put("list", dtos);
		map.put("query", dto);
		return "admin/company/company_sel";
	}
}
